package com.github.baichuan.application.scaffold.rest.controller;

import com.github.baichuan.application.scaffold.rest.domain.application.Application;
import com.github.baichuan.application.scaffold.rest.domain.application.ApplicationService;
import com.github.baichuan.application.scaffold.rest.domain.authorization.Role;
import com.github.baichuan.application.scaffold.rest.domain.authorization.RoleService;
import com.github.baichuan.application.scaffold.rest.domain.identity.ApplicationMember;
import com.github.baichuan.application.scaffold.rest.domain.identity.ApplicationMemberService;
import com.github.baichuan.application.scaffold.rest.jpa.authorization.RoleSpecification;
import com.github.baichuan.mapping.BeanMapper;
import com.github.baichuan.web.dto.Pagination;
import com.github.baichuan.web.dto.PaginationCriteria;
import com.github.baichuan.web.dto.Result;
import com.github.baichuan.application.scaffold.rest.dto.role.RoleAuthorization;
import com.github.baichuan.application.scaffold.rest.dto.role.RoleForm;
import com.github.baichuan.application.scaffold.rest.dto.role.RoleGridView;
import com.github.baichuan.application.scaffold.rest.dto.role.RoleQueryCriteria;
import com.github.baichuan.web.ui.select.OptionItem;
import com.github.baichuan.web.security.Authorization;
import com.github.baichuan.web.servlet.Restful;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Tag(name = "角色")
@RequestMapping("/role")
public class RoleController {

    @Autowired
    public RoleController(RoleService roleService, ApplicationService applicationService,
                          ApplicationMemberService memberService) {
        this.roleService = roleService;
        this.applicationService = applicationService;
        this.memberService = memberService;
    }

    private RoleService roleService;
    private ApplicationService applicationService;
    private ApplicationMemberService memberService;

    @PostMapping("/query")
    @Operation(summary = "查询")
//    @Authorization("role:query")
    public ResponseEntity<Pagination<RoleGridView>> query(@RequestHeader("x-application-code") @Parameter(hidden = true) String applicationCode,
                                @RequestHeader(value = "x-member-uid") String memberUid,
                                @RequestBody PaginationCriteria<RoleQueryCriteria> paginationCriteria)
            throws NoSuchFieldException {
        RoleQueryCriteria criteria = paginationCriteria.getCriteria();
        Application application = applicationService.findByCode(applicationCode);

        ApplicationMember applicationMember = memberService.find(memberUid);
        RoleSpecification specification = criteria.specification(application, applicationMember);
        Page<RoleGridView> page = roleService.query(specification, paginationCriteria.pageable(RoleGridView.class))
                .map(x -> BeanMapper.map(x, RoleGridView.class));

        return ResponseEntity.ok(Pagination.of(page));
    }

    @GetMapping("/{id}")
    @Operation(summary = "表单数据")
    public ResponseEntity<RoleForm> get(@PathVariable("id") String id) {
        Role role = roleService.find(id);
        RoleForm form = BeanMapper.map(role, RoleForm.class);
        return ResponseEntity.ok(form);
    }

    @GetMapping("/options")
    @Operation(summary = "获取角色选项")
    public ResponseEntity<List<OptionItem>> options(@RequestHeader("x-application-code") @Parameter(hidden = true) String applicationCode,
                                  @RequestHeader("x-member-uid") String memberUid) {
        Application application = applicationService.findByCode(applicationCode);
        ApplicationMember applicationMember = memberService.find(applicationCode, memberUid);

        RoleSpecification specification = RoleSpecification.builder()
                .application(application)
                .applicationMember(applicationMember)
                .build();

        List<OptionItem> options = roleService.get(specification).stream()
                .sorted(Comparator.comparing(Role::getName))
                .map(role -> OptionItem.of(role.getName(), role.getId()))
                .collect(Collectors.toList());
        return ResponseEntity.ok(options);
    }

//    @GetMapping(value = {"/assignable/options", "/assignable/options/{uid}"})
//    @Operation(summary = "获取角色选项")
//    public ResponseEntity assignable(@PathVariable(value = "uid", required = false) String uid,
//                                     @RequestHeader("x-application-code") @Parameter(hidden = true) String application, @RequestHeader("x-member-uid") String memberUid) {
//        Application app = applicationService.findByCode(application);
//        ApplicationMember applicationMember = memberService.find(application, memberUid);
//        RoleSpecification specification = RoleSpecification.builder().application(app).applicationMember(applicationMember).build();
//        List<Role> roles = roleService.get(specification);
//        //非管理员
//        if (ObjectUtils.isNotEmpty(applicationMember) && !applicationMember.getMemberType().equals("ADMIN")) {
//            //用户自身的角色
//            List<Role> owns = applicationMember.getRoles();
//            roles.addAll(owns);
//            if (StringUtils.isNotBlank(uid)) {
//                //被修改用户的角色
//                ApplicationMember member = memberService.find(application, uid);
//                List<Role> fixes = member.getRoles();
//                roles.addAll(fixes);
//            }
//            //去重
//            roles = roles.stream().distinct().collect(Collectors.toList());
//        }
//        List<Option> result = roles.stream().sorted(Comparator.comparing(Role::getName))
//                .map(role -> new Option(role.getName(), role.getId()))
//                .collect(Collectors.toList());
//        return ResponseEntity.ok(result);
//    }

    @PostMapping
    @Operation(summary = "添加")
    @Authorization("role:add")
    public ResponseEntity<Result> add(@RequestHeader("x-application-code") @Parameter(hidden = true) String application,
                              @RequestHeader("x-member-uid") String memberUid,
                              @RequestBody @Valid RoleForm form) {
        Result result = roleService.add(application, memberUid, form);
        return Restful.created(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改")
    @Authorization("role:edit")
    public ResponseEntity<Result> edit(@RequestHeader("x-application-code") @Parameter(hidden = true) String application,
                                       @PathVariable("id") String id, @RequestBody @Valid RoleForm form) {
        Result result = roleService.edit(application, id, form);
        return ResponseEntity.ok(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除")
    @Authorization("role:remove")
    public ResponseEntity<Result> delete(@RequestHeader("x-application-code") @Parameter(hidden = true) String application,
                                         @PathVariable("id") String id) {
        Result result = roleService.remove(application, id);
        return Restful.response(result);
    }

    @PutMapping("/authorize")
    @Operation(summary = "添加角色授权")
    public ResponseEntity<Result> addAuthorize(@RequestHeader("x-application-code") @Parameter(hidden = true) String application,
                                       @RequestBody @Validated RoleAuthorization authorization) {
        Result result = roleService.addAuthorize(application, authorization.getRoleId(), authorization.getResourceId());
        return Restful.response(result);
    }

    @DeleteMapping("/authorize")
    @Operation(summary = "移除角色授权")
    public ResponseEntity<Result> removeAuthorize(@RequestHeader("x-application-code") @Parameter(hidden = true) String application,
                                          @RequestBody @Validated RoleAuthorization authorization) {
        Result result = roleService.removeAuthorize(application, authorization.getRoleId(), authorization.getResourceId());
        return Restful.response(result);
    }

    @GetMapping("/{id}/authorized")
    @Operation(summary = "获取角色已授权的权限代码")
    public ResponseEntity<List<String>> authorized(@RequestHeader("x-application-code") @Parameter(hidden = true) String application,
                                                   @PathVariable("id") String id) {
        List<String> ids = roleService.getResources(application, id).stream()
                .map(r -> r.getId()).collect(Collectors.toList());
        return ResponseEntity.ok(ids);
    }
}
